//
//  PackageBuilder.java
//  Adjust SDK
//
//  Created by Christian Wellenbrock (@wellle) on 25th June 2013.
//  Copyright (c) 2013-2018 Adjust GmbH. All rights reserved.
//

package com.db.adjust;

import android.content.TextUtils;
import com.db.adjust.algorithm.adj4.codesign;
import com.db.env.ReferrerDetails;
import com.db.utils.*;
import org.json.JSONObject;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


public class PackageBuilder {
    //    private static ILogger logger = AdjustFactory.getLogger();
    private long createdAt;
    private DeviceInfo deviceInfo;
    private AdjustConfig adjustConfig;
    private ActivityStateCopy activityStateCopy;
    private SessionParameters sessionParameters;

    long clickTimeInSeconds = -1;
    long clickTimeInMilliseconds = -1;
    long installBeginTimeInSeconds = -1;
    long clickTimeServerInSeconds = -1;
    long installBeginTimeServerInSeconds = -1;
    String reftag;
    String deeplink;
    String referrer;
    String installVersion;
    String rawReferrer;
    String referrerApi;
    String preinstallPayload;
    String preinstallLocation;
    Boolean googlePlayInstant;
    AdjustAttribution attribution;
    Map<String, String> extraParameters;
    public String iso;

    public long skadnRegisteredAt;

    public String target;

    public String algorithm;

    public String signatureMeta;

    public String adjustAlgoType;

    public String programme;

    private class ActivityStateCopy {
        int eventCount = -1;
        int sessionCount = -1;
        int subsessionCount = -1;
        long timeSpent = -1;
        long lastInterval = -1;
        long sessionLength = -1;
        String uuid = null;
        String externalDeviceId = null;
        String pushToken = null;

        ActivityStateCopy(ActivityState activityState) {
            if (activityState == null) {
                return;
            }
            this.eventCount = activityState.eventCount;
            this.sessionCount = activityState.sessionCount;
            this.subsessionCount = activityState.subsessionCount;
            this.timeSpent = activityState.timeSpent;
            this.lastInterval = activityState.lastInterval;
            this.sessionLength = activityState.sessionLength;
            this.uuid = activityState.uuid;
            this.externalDeviceId = activityState.externalDeviceId;
            this.pushToken = activityState.pushToken;
        }
    }

    public PackageBuilder(AdjustConfig adjustConfig, DeviceInfo deviceInfo, ActivityState activityState, SessionParameters sessionParameters) {
        this.deviceInfo = deviceInfo;
        this.adjustConfig = adjustConfig;
        this.activityStateCopy = new ActivityStateCopy(activityState);
        this.sessionParameters = sessionParameters;
    }

    public void updateCreateTime(long createdAt) {
        this.createdAt = createdAt;
    }

    public void updateSkadnRegisteredAt(long skadnRegisteredAt) {
        this.skadnRegisteredAt = skadnRegisteredAt;
    }

    private String getTarget(Map<String, String> parameters) {
        String target = this.target;
        if (TextUtils.isEmpty(target)) {
            target = parameters.get("package_name");
            if (target == null) {
                target = parameters.get("bundle_id");
            }
        }
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    public String getAlgorithm() {
        return algorithm;
    }

    public String getSignatureMeta() {
        return signatureMeta;
    }

    public void setSignatureMeta(String signatureMeta) {
        this.signatureMeta = signatureMeta;
    }

    public String getAdjustAlgoType() {
        return adjustAlgoType;
    }

    public void setAdjustAlgoType(String adjustAlgoType) {
        this.adjustAlgoType = adjustAlgoType;
    }

    public String getProgramme() {
        return programme;
    }

    public void setProgramme(String programme) {
        this.programme = programme;
    }

    public ActivityPackage buildSessionPackage(String uuid, String way) {
        Map<String, String> parameters = getSessionParameters();
        ActivityPackage sessionPackage = getDefaultActivityPackage(ActivityKind.SESSION);
        sessionPackage.setPath("/session");
        sessionPackage.setSuffix("");
        System.out.println("session:" + parameters);
//        AdjustSigner.sign(parameters, ActivityKind.SESSION.toString(),
//                sessionPackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);
        parameters.put("activity_kind", sessionPackage.getActivityKind().toString());
        parameters.put("client_sdk", sessionPackage.getClientSdk());

        if (Arrays.asList("adj5", "adj6", "adj7").contains(way)) {
            parameters.put("foreground", "1");
            parameters.put("offline_mode_enabled", "0");
            parameters.put("tracking_enabled", "1");
            parameters.put("ui_mode", "1");
            // 测试
            parameters.put("enqueue_size", "0");
            parameters.put("wait_total", "0.0");
            parameters.put("last_error", "0");
            parameters.put("first_error", "0");
            parameters.put("wait_time", "0.0");
            parameters.put("retry_count", "0");
        }

        String target = getTarget(parameters);
        LogUtil.logApp("buildSessionPackage", "uuid:" + uuid + ", before buildSessionParams:" + parameters);
        Map<String, String> signedParameters = fetchSignature(parameters, target);
        sessionPackage.setParameters(signedParameters);
        LogUtil.logApp("buildSessionPackage", "uuid:" + uuid + ", after buildSessionParams:" + signedParameters);

        return sessionPackage;
    }


    public Map fetchSignature(Map<String, String> parameters, String target) {

        JSONObject requestJSON = new JSONObject();
        requestJSON.put("id", UUID.randomUUID().toString());
        requestJSON.put("package", target);
        requestJSON.put("parameters", new JSONObject(parameters));
        requestJSON.put("signatureMeta", getSignatureMeta());
        requestJSON.put("algorithm", getAlgorithm());
        requestJSON.put("programme", getProgramme());

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        // signer接口
        String adjApi = PropertiesUtil.getSignerApi();
        String respStr = Downloader.doDownload(adjApi, "POST", requestJSON.toString(), headers);

        JSONObject respJSON = new JSONObject(respStr);
        if (!"0".equals(respJSON.get("code"))) {
            LogUtil.logApp("Fetch Signature", "Response Error:" + respJSON.get("msg"));
            return null;
        }
        return respJSON.getJSONObject("data").toMap();
    }

    ActivityPackage buildEventPackage(AdjustEvent event, boolean isInDelay) {
        Map<String, String> parameters = getEventParameters(event, isInDelay);
        ActivityPackage eventPackage = getDefaultActivityPackage(ActivityKind.EVENT);
        eventPackage.setPath("/event");
        eventPackage.setSuffix(getEventSuffix(event));

//        AdjustSigner.sign(parameters, ActivityKind.EVENT.toString(),
//                eventPackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);

        eventPackage.setParameters(parameters);

        if (isInDelay) {
            eventPackage.setCallbackParameters(event.callbackParameters);
            eventPackage.setPartnerParameters(event.partnerParameters);
        }

        return eventPackage;
    }

//    ActivityPackage buildInfoPackage(String source) {
//        Map<String, String> parameters = getInfoParameters(source);
//        ActivityPackage infoPackage = getDefaultActivityPackage(ActivityKind.INFO);
//        infoPackage.setPath("/sdk_info");
//        infoPackage.setSuffix("");
//

    /// /        AdjustSigner.sign(parameters, ActivityKind.INFO.toString(),
    /// /                infoPackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);
//
//        infoPackage.setParameters(parameters);
//        return infoPackage;
//    }
    public ActivityPackage buildClickPackage(String source, String uuid, String way) {
        Map<String, String> parameters = getClickParameters(source);
        ActivityPackage clickPackage = getDefaultActivityPackage(ActivityKind.CLICK);
        clickPackage.setPath("/sdk_click");
        clickPackage.setSuffix("");

        parameters.put("activity_kind", clickPackage.getActivityKind().toString());
        parameters.put("client_sdk", clickPackage.getClientSdk());

        if (Arrays.asList("adj5", "adj6", "adj7").contains(way)) {
            parameters.put("foreground", "1");
            parameters.put("offline_mode_enabled", "0");
            parameters.put("tracking_enabled", "1");
            parameters.put("ui_mode", "1");
        }

        String target = getTarget(parameters);
        LogUtil.logApp("buildClickPackage", "uuid:" + uuid + ", before buildClickParams:" + parameters);
        Map<String, String> signedParameters = fetchSignature(parameters, target);
        clickPackage.setParameters(signedParameters);
        LogUtil.logApp("buildClickPackage", "uuid:" + uuid + ", after buildClickParams:" + signedParameters);

        return clickPackage;
    }

    public ActivityPackage buildAttributionPackage(String initiatedByDescription, String uuid, String way) {
        Map<String, String> parameters = getAttributionParameters(initiatedByDescription);
        ActivityPackage attributionPackage = getDefaultActivityPackage(ActivityKind.ATTRIBUTION);
        attributionPackage.setPath("attribution"); // does not contain '/' because of Uri.Builder.appendPath
        attributionPackage.setSuffix("");

        parameters.put("activity_kind", attributionPackage.getActivityKind().toString());
        parameters.put("client_sdk", attributionPackage.getClientSdk());

        if (Arrays.asList("adj5", "adj6", "adj7").contains(way)) {
            parameters.put("foreground", "1");
            parameters.put("offline_mode_enabled", "0");
            parameters.put("tracking_enabled", "1");
            parameters.put("ui_mode", "1");
        }

        String target = getTarget(parameters);
        LogUtil.logApp("buildAttributionPackage", "uuid:" + uuid + ", before buildAttributionParams:" + parameters);
        Map<String, String> signedParameters = fetchSignature(parameters, target);
        attributionPackage.setParameters(signedParameters);
        LogUtil.logApp("buildAttributionPackage", "uuid:" + uuid + ", after buildAttributionParams:" + signedParameters);

        return attributionPackage;
    }

//    ActivityPackage buildGdprPackage() {
//        Map<String, String> parameters = getGdprParameters();
//        ActivityPackage gdprPackage = getDefaultActivityPackage(ActivityKind.GDPR);
//        gdprPackage.setPath("/gdpr_forget_device");
//        gdprPackage.setSuffix("");
//
////        AdjustSigner.sign(parameters, ActivityKind.GDPR.toString(),
////                gdprPackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);
//
//        gdprPackage.setParameters(parameters);
//        return gdprPackage;
//    }

//    ActivityPackage buildDisableThirdPartySharingPackage() {
//        Map<String, String> parameters = getDisableThirdPartySharingParameters();
//        ActivityPackage activityPackage = getDefaultActivityPackage(ActivityKind.DISABLE_THIRD_PARTY_SHARING);
//        activityPackage.setPath("/disable_third_party_sharing");
//        activityPackage.setSuffix("");
//
////        AdjustSigner.sign(parameters, ActivityKind.DISABLE_THIRD_PARTY_SHARING.toString(),
////                activityPackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);
//
//        activityPackage.setParameters(parameters);
//        return activityPackage;
//    }

//    ActivityPackage buildAdRevenuePackage(String source, JSONObject adRevenueJson) {
//        Map<String, String> parameters = getAdRevenueParameters(source, adRevenueJson);
//        ActivityPackage adRevenuePackage = getDefaultActivityPackage(ActivityKind.AD_REVENUE);
//        adRevenuePackage.setPath("/ad_revenue");
//        adRevenuePackage.setSuffix("");
//

    /// /        AdjustSigner.sign(parameters, ActivityKind.AD_REVENUE.toString(),
    /// /                adRevenuePackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);
//
//        adRevenuePackage.setParameters(parameters);
//        return adRevenuePackage;
//    }

//    ActivityPackage buildSubscriptionPackage(AdjustPlayStoreSubscription subscription, boolean isInDelay) {
//        Map<String, String> parameters = getSubscriptionParameters(subscription, isInDelay);
//        ActivityPackage subscriptionPackage = getDefaultActivityPackage(ActivityKind.SUBSCRIPTION);
//        subscriptionPackage.setPath("/v2/purchase");
//        subscriptionPackage.setSuffix("");
//
//        AdjustSigner.sign(parameters, ActivityKind.SUBSCRIPTION.toString(),
//                subscriptionPackage.getClientSdk(), adjustConfig.context, adjustConfig.logger);
//
//        subscriptionPackage.setParameters(parameters);
//        return subscriptionPackage;
//    }
    private Map<String, String> getSessionParameters() {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
        Map<String, String> parameters = new HashMap<String, String>();

//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);//nonPlayParameters = invokeStaticMethod("com.adjust.sdk.imei.Util", "getImeiParameters", new Class[]{Context.class, ILogger.class}, context, logger);
        Map<String, String> imeiParameters = null;
        // Check if plugin is used and if yes, add read parameters.
        if (imeiParameters != null) {
            parameters.putAll(imeiParameters);
        }

        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);//invokeStaticMethod("com.adjust.sdk.oaid.Util", "getOaidParameters", new Class[]{Context.class, ILogger.class}, context, logger);
        Map<String, String> oaidParameters = null;
        if (oaidParameters != null) {
            parameters.putAll(oaidParameters);
        }

        // Callback and partner parameters.
//        if(this.sessionParameters.callbackParameterStr != null){
//            PackageBuilder.addString(parameters,"callback_params",this.sessionParameters.getCallbackParameterStr());
//        }
//        if(this.sessionParameters.partnerParameterStr != null){
//            PackageBuilder.addString(parameters,"partner_params",this.sessionParameters.getPartnerParameterStr());;
//        }

        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
        }
        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);//1
        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);//gaid
        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);//service
        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);//[1,3]

        if (!containsPlayIds(parameters)) {//should never run into
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
        }

        // Rest of the parameters.
        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);//23
        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);//should hook in AdjustConfig.setAppSecret
        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);//should hook in AdjustConfig.init
        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);//versionName
        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
        PackageBuilder.addLong(parameters, "connectivity_type", deviceInfo.networkInfo.type);//WIFI=1 TYPE_MOBILE=0
        PackageBuilder.addString(parameters, "country", deviceInfo.country);//US VN
        PackageBuilder.addString(parameters, "cpu_type", deviceInfo.abi);//ro.product.cpu.abilist  [0]
        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt, this.iso);//now
        PackageBuilder.addString(parameters, "default_tracker", adjustConfig.defaultTracker);//should hook in AdjustConfig.setDefaultTracker
        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);//should hoook in AdjustConfig.setDeviceKnown
        PackageBuilder.addString(parameters, "device_manufacturer", deviceInfo.deviceManufacturer);//Build.MANUFACTURER
        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);//Build.MODEL
        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);//getDeviceType
        PackageBuilder.addString(parameters, "display_height", deviceInfo.displayHeight);//getDisplayHeight
        PackageBuilder.addString(parameters, "display_width", deviceInfo.displayWidth);//getDisplayWidth
        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);//should hook in AdjustConfig.init

        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);//should hook in AdjustConfig

//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);//should hook in AdjustConfig.setExternalDeviceId

        if (adjustConfig.externalDeviceId) {
            // 某些特殊的包会上传此参数，如：yandex
            PackageBuilder.addString(parameters, "external_device_id", activityStateCopy.externalDeviceId);
        }

        PackageBuilder.addString(parameters, "fb_id", deviceInfo.fbAttributionId);
//        PackageBuilder.addString(parameters, "fire_adid", Util.getFireAdvertisingId(contentResolver));//advertising_id
        PackageBuilder.addString(parameters, "fire_adid", null);//advertising_id  amazon device
//        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", Util.getFireTrackingEnabled(contentResolver));
        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", null);
        PackageBuilder.addString(parameters, "hardware_name", deviceInfo.hardwareName);//Build.DISPLAY  ro.build.display.id
        PackageBuilder.addString(parameters, "installed_at", deviceInfo.appInstallTime);
        PackageBuilder.addString(parameters, "language", deviceInfo.language);//en
        PackageBuilder.addDuration(parameters, "last_interval", activityStateCopy.lastInterval);
//        PackageBuilder.addDuration(parameters, "last_interval", -1);//
//        PackageBuilder.addString(parameters, "mcc", Util.getMcc(adjustConfig.context));
//        PackageBuilder.addString(parameters, "mnc", Util.getMnc(adjustConfig.context));
        PackageBuilder.addString(parameters, "mcc", deviceInfo.mcc);
        PackageBuilder.addString(parameters, "mnc", deviceInfo.mnc);
        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
//        PackageBuilder.addLong(parameters, "network_type", Util.getNetworkType(adjustConfig.context));

        //todo check network_type
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addLong(parameters, "network_type", 13);//NETWORK_TYPE_UNKNOWN = 0; NETWORK_TYPE_LTE = 13;  TelephonyManager
        }
        PackageBuilder.addString(parameters, "os_build", deviceInfo.buildName);//Build.ID
        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);//
//        PackageBuilder.addString(parameters, "os_name", "android");//
        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);//Build.VERSION.RELEASE;
        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);//should be hook in ActivityHandler.setPushToken
        PackageBuilder.addString(parameters, "screen_density", deviceInfo.screenDensity);
        PackageBuilder.addString(parameters, "screen_format", deviceInfo.screenFormat);
        PackageBuilder.addString(parameters, "screen_size", deviceInfo.screenSize);
        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);//should hook in AdjustConfig.setAppSecret
        PackageBuilder.addLong(parameters, "session_count", activityStateCopy.sessionCount);
//        PackageBuilder.addLong(parameters, "session_count", 1);
        PackageBuilder.addDuration(parameters, "session_length", activityStateCopy.sessionLength);
//        PackageBuilder.addDuration(parameters, "session_length", -1);
        PackageBuilder.addLong(parameters, "subsession_count", activityStateCopy.subsessionCount);
//        PackageBuilder.addLong(parameters, "subsession_count", -1);
        PackageBuilder.addDuration(parameters, "time_spent", activityStateCopy.timeSpent);
//        PackageBuilder.addDuration(parameters, "time_spent", -1);
        PackageBuilder.addString(parameters, "updated_at", deviceInfo.appUpdateTime);


        PackageBuilder.addString(parameters, "app_version_short", deviceInfo.shortVersion);
        PackageBuilder.addString(parameters, "att_status", deviceInfo.attStatus);
        PackageBuilder.addString(parameters, "bundle_id", deviceInfo.bundleID);
        PackageBuilder.addString(parameters, "idfv", deviceInfo.idfv);
        PackageBuilder.addString(parameters, "idfa", deviceInfo.idfa);
        PackageBuilder.addString(parameters, "primary_dedupe_token", deviceInfo.primaryDedupeToken);
        PackageBuilder.addDateInMilliseconds(parameters, "skadn_registered_at", this.skadnRegisteredAt, iso);
        PackageBuilder.addString(parameters, "started_at", deviceInfo.startAt);
        if (deviceInfo.hasFbAnonId) {
            PackageBuilder.addString(parameters, "fb_anon_id", "XZ" + UUID.randomUUID().toString().toUpperCase());
        }

        checkDeviceIds(parameters);
        return parameters;
    }

    public Map<String, String> getEventParameters(AdjustEvent event, boolean isInDelay) {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
        Map<String, String> parameters = new HashMap<String, String>();
//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);
        Map<String, String> imeiParameters = null;
        // Check if plugin is used and if yes, add read parameters.
        if (imeiParameters != null) {
            parameters.putAll(imeiParameters);
        }

        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);
        Map<String, String> oaidParameters = null;
        if (oaidParameters != null) {
            parameters.putAll(oaidParameters);
        }

        // Callback and partner parameters.
        if (!isInDelay) {
//            PackageBuilder.addMapJson(parameters, "callback_params", Util.mergeParameters(this.sessionParameters.callbackParameters, event.callbackParameters, "Callback"));
//            PackageBuilder.addMapJson(parameters, "partner_params", Util.mergeParameters(this.sessionParameters.partnerParameters, event.partnerParameters, "Partner"));
        }

        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
        }
        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);

        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
        }

        // Rest of the parameters.
        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
        PackageBuilder.addLong(parameters, "connectivity_type", deviceInfo.networkInfo.type);
        PackageBuilder.addString(parameters, "country", deviceInfo.country);
        PackageBuilder.addString(parameters, "cpu_type", deviceInfo.abi);
        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt, this.iso);
        PackageBuilder.addString(parameters, "currency", event.currency);
        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
        PackageBuilder.addString(parameters, "device_manufacturer", deviceInfo.deviceManufacturer);
        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
        PackageBuilder.addString(parameters, "display_height", deviceInfo.displayHeight);
        PackageBuilder.addString(parameters, "display_width", deviceInfo.displayWidth);
        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
        PackageBuilder.addString(parameters, "event_callback_id", event.callbackId);
        PackageBuilder.addLong(parameters, "event_count", activityStateCopy.eventCount);
        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
        PackageBuilder.addString(parameters, "event_token", event.eventToken);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
        if (adjustConfig.externalDeviceId) {
            PackageBuilder.addString(parameters, "external_device_id", activityStateCopy.externalDeviceId);
        }

        PackageBuilder.addString(parameters, "fb_id", deviceInfo.fbAttributionId);
        PackageBuilder.addString(parameters, "fire_adid", null);
        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", null);
        PackageBuilder.addString(parameters, "hardware_name", deviceInfo.hardwareName);
        PackageBuilder.addString(parameters, "language", deviceInfo.language);
        PackageBuilder.addString(parameters, "mcc", deviceInfo.mcc);
        PackageBuilder.addString(parameters, "mnc", deviceInfo.mnc);
        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addLong(parameters, "network_type", 13);
        }
        PackageBuilder.addString(parameters, "os_build", deviceInfo.buildName);
        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
        PackageBuilder.addDouble(parameters, "revenue", event.revenue);
        PackageBuilder.addString(parameters, "screen_density", deviceInfo.screenDensity);
        PackageBuilder.addString(parameters, "screen_format", deviceInfo.screenFormat);
        PackageBuilder.addString(parameters, "screen_size", deviceInfo.screenSize);
        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
        PackageBuilder.addLong(parameters, "session_count", activityStateCopy.sessionCount);
        PackageBuilder.addDuration(parameters, "session_length", activityStateCopy.sessionLength);
        PackageBuilder.addLong(parameters, "subsession_count", activityStateCopy.subsessionCount);
        PackageBuilder.addDuration(parameters, "time_spent", activityStateCopy.timeSpent);

        checkDeviceIds(parameters);
        return parameters;
    }

//    private Map<String, String> getInfoParameters(String source) {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
//        Map<String, String> parameters = new HashMap<String, String>();
//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);
//
//        // Check if plugin is used and if yes, add read parameters.
//        if (imeiParameters != null) {
//            parameters.putAll(imeiParameters);
//        }
//
//        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);
//        if (oaidParameters != null) {
//            parameters.putAll(oaidParameters);
//        }
//
//        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
//        PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
//        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
//        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
//        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
//        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);
//
//        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
//            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
//            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
//            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
//        }
//
//        // Rest of the parameters.
//        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
//        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
//        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
//        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt);
//        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
//        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
//        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
//        PackageBuilder.addString(parameters, "fire_adid", Util.getFireAdvertisingId(contentResolver));
//        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", Util.getFireTrackingEnabled(contentResolver));
//        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
//        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
//        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
//        PackageBuilder.addString(parameters, "source", source);
//
//        checkDeviceIds(parameters);
//        return parameters;
//    }

    private Map<String, String> getClickParameters(String source) {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
        Map<String, String> parameters = new HashMap<>();
        Map<String, String> imeiParameters = null;

        // Check if plugin is used and if yes, add read parameters.
        if (imeiParameters != null) {
            parameters.putAll(imeiParameters);
        }

        // Check if oaid plugin is used and if yes, add the parameter
        Map<String, String> oaidParameters = null;
        if (oaidParameters != null) {
            parameters.putAll(oaidParameters);
        }

        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
        }
        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);

        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
        }

        // Attribution parameters.
        if (attribution != null) {
            PackageBuilder.addString(parameters, "tracker", attribution.trackerName);
            PackageBuilder.addString(parameters, "campaign", attribution.campaign);
            PackageBuilder.addString(parameters, "adgroup", attribution.adgroup);
            PackageBuilder.addString(parameters, "creative", attribution.creative);
        }

        // Rest of the parameters.
        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
//        if(this.sessionParameters.callbackParameterStr != null){
//            PackageBuilder.addString(parameters,"callback_params",this.sessionParameters.getCallbackParameterStr());;
//        }

        PackageBuilder.addDateInSeconds(parameters, "click_time", clickTimeInSeconds, this.iso);
        PackageBuilder.addDateInSeconds(parameters, "click_time_server", clickTimeServerInSeconds, this.iso);
        PackageBuilder.addLong(parameters, "connectivity_type", deviceInfo.networkInfo.type);
        PackageBuilder.addString(parameters, "country", deviceInfo.country);
        PackageBuilder.addString(parameters, "cpu_type", deviceInfo.abi);
        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt, this.iso);
        PackageBuilder.addString(parameters, "deeplink", deeplink);
        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
        PackageBuilder.addString(parameters, "device_manufacturer", deviceInfo.deviceManufacturer);
        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
        PackageBuilder.addString(parameters, "display_height", deviceInfo.displayHeight);
        PackageBuilder.addString(parameters, "display_width", deviceInfo.displayWidth);
        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
        if (adjustConfig.externalDeviceId) {
            PackageBuilder.addString(parameters, "external_device_id", activityStateCopy.externalDeviceId);
        }

        PackageBuilder.addString(parameters, "fb_id", deviceInfo.fbAttributionId);
        PackageBuilder.addString(parameters, "fire_adid", null);
        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", null);
        PackageBuilder.addBoolean(parameters, "google_play_instant", googlePlayInstant);
        PackageBuilder.addString(parameters, "hardware_name", deviceInfo.hardwareName);
        PackageBuilder.addDateInSeconds(parameters, "install_begin_time", installBeginTimeInSeconds, this.iso);
        PackageBuilder.addDateInSeconds(parameters, "install_begin_time_server", installBeginTimeServerInSeconds, this.iso);
        PackageBuilder.addString(parameters, "install_version", installVersion);
        PackageBuilder.addString(parameters, "installed_at", deviceInfo.appInstallTime);
        PackageBuilder.addString(parameters, "language", deviceInfo.language);
        PackageBuilder.addDuration(parameters, "last_interval", activityStateCopy.lastInterval);
        PackageBuilder.addString(parameters, "mcc", deviceInfo.mcc);
        PackageBuilder.addString(parameters, "mnc", deviceInfo.mnc);
        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addLong(parameters, "network_type", 13);
        }
        PackageBuilder.addString(parameters, "os_build", deviceInfo.buildName);
//        PackageBuilder.addString(parameters, "os_name", "android");
        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
        PackageBuilder.addMapJson(parameters, "params", extraParameters);//todo should be null
//        PackageBuilder.addMapJson(parameters, "partner_params", this.sessionParameters.partnerParameters);
        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
        PackageBuilder.addString(parameters, "raw_referrer", rawReferrer);//todo should be null
        PackageBuilder.addString(parameters, "referrer", referrer);//utm_source=google-play&utm_medium=organic
        PackageBuilder.addString(parameters, "referrer_api", referrerApi);//google
        PackageBuilder.addString(parameters, "reftag", reftag);//todo should be null
        PackageBuilder.addString(parameters, "screen_density", deviceInfo.screenDensity);
        PackageBuilder.addString(parameters, "screen_format", deviceInfo.screenFormat);
        PackageBuilder.addString(parameters, "screen_size", deviceInfo.screenSize);
        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
        PackageBuilder.addLong(parameters, "session_count", activityStateCopy.sessionCount);
//        PackageBuilder.addDuration(parameters, "session_length", activityStateCopy.sessionLength);
        PackageBuilder.addDuration(parameters, "session_length", 0);
        PackageBuilder.addString(parameters, "source", source);
//        PackageBuilder.addLong(parameters, "subsession_count", activityStateCopy.subsessionCount);
        PackageBuilder.addLong(parameters, "subsession_count", 1);
//        PackageBuilder.addDuration(parameters, "time_spent", activityStateCopy.timeSpent);
        PackageBuilder.addDuration(parameters, "time_spent", 0);
        PackageBuilder.addString(parameters, "updated_at", deviceInfo.appUpdateTime);
        PackageBuilder.addString(parameters, "payload", preinstallPayload);
        PackageBuilder.addString(parameters, "found_location", preinstallLocation);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addBoolean(parameters, "is_click", true);

        } else {
//            PackageBuilder.addString(parameters, "attribution_token", "hhvJBLVXXfZMaZ/RRWdaFEUiWiIpNPQgLT/xr7YdtIEc7HPaT668KAIeeNKAOL+GDmP7FTWBDtWfDpEKffAxrIPblit0PYIn2gAAAVADAAAAnwAAAIAh/zaO43YEZHm4yA7fhzKGcj+5nWyYePHsJHPH+V4T7MhijWidJA8YDk8aD0prCXoUN4nE1c\n" +
//                    "        8te1sTNaUn77c9rFu6asNUhSYA4BnTycy64ppHs4uZQwzKBhPaCwDaYxUPx750QP0ecQtSBWpw4xG1pSwjEe82JeGU2kx+FqHKVgAAABvixQNyBrU13nsMuaWwsn86fh5RU2btHGQjEMQAAACfAY06uqhcDrGOOTaOODn0bVUVfoEMAAAAhgcBgKkFMKzo9v+m9HSzLZqjEWXRr7xzkrH\n" +
//                    "        9Gjk/4m4FGhg8pGzj1Q5B4NM/zJwIpPR2UJgjLHLtgriEM5H3ckKbn2wPX586z16xJz1xz8G2ZU18ST1v71NE5HNskUV7p3SUAHeHS9xiIQH9SYEbvPd5Qh3ht1amf/lczeBYDVysl1sewdbmAAAAAAABBEcLAAA=");
        }

        PackageBuilder.addString(parameters, "app_version_short", deviceInfo.shortVersion);

        if (deviceInfo.osName.equalsIgnoreCase("ios")) {
            // attStatus测试
            PackageBuilder.addString(parameters, "att_status", deviceInfo.attStatus);
        }

        if (deviceInfo.osName.equalsIgnoreCase("android")) {
            PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
        }

        PackageBuilder.addString(parameters, "bundle_id", deviceInfo.bundleID);
        PackageBuilder.addString(parameters, "idfv", deviceInfo.idfv);
        PackageBuilder.addString(parameters, "idfa", deviceInfo.idfa);
        PackageBuilder.addString(parameters, "primary_dedupe_token", deviceInfo.primaryDedupeToken);
        PackageBuilder.addDateInMilliseconds(parameters, "skadn_registered_at", this.skadnRegisteredAt, iso);
        PackageBuilder.addString(parameters, "started_at", deviceInfo.startAt);
        if (deviceInfo.hasFbAnonId) {
            PackageBuilder.addString(parameters, "fb_anon_id", "XZ" + UUID.randomUUID().toString().toUpperCase());
        }

        checkDeviceIds(parameters);

        PackageBuilder.addBoolean(parameters, "last_interval", false);

        return parameters;
    }

    private Map<String, String> getAttributionParameters(String initiatedBy) {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
        Map<String, String> parameters = new HashMap<String, String>();
        Map<String, String> imeiParameters = null;

        // Check if plugin is used and if yes, add read parameters.
        if (imeiParameters != null) {
            parameters.putAll(imeiParameters);
        }

        // Check if oaid plugin is used and if yes, add the parameter
        Map<String, String> oaidParameters = null;
        if (oaidParameters != null) {
            parameters.putAll(oaidParameters);
        }

        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
        if ("android".equals(deviceInfo.osName)) {
            PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
        }
        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);

        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
        }

        // Rest of the parameters.
        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt, this.iso);
        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
        if (adjustConfig.externalDeviceId) {
            PackageBuilder.addString(parameters, "external_device_id", activityStateCopy.externalDeviceId);
        }

        PackageBuilder.addString(parameters, "fire_adid", null);
        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", null);
        PackageBuilder.addString(parameters, "initiated_by", initiatedBy);//todo check backend
        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);

        PackageBuilder.addString(parameters, "app_version_short", deviceInfo.shortVersion);
        PackageBuilder.addString(parameters, "att_status", deviceInfo.attStatus);
        PackageBuilder.addString(parameters, "bundle_id", deviceInfo.bundleID);
        PackageBuilder.addString(parameters, "idfv", deviceInfo.idfv);
        PackageBuilder.addString(parameters, "idfa", deviceInfo.idfa);
        PackageBuilder.addString(parameters, "primary_dedupe_token", deviceInfo.primaryDedupeToken);
        PackageBuilder.addDateInMilliseconds(parameters, "skadn_registered_at", this.skadnRegisteredAt, iso);
        PackageBuilder.addString(parameters, "started_at", deviceInfo.startAt);

        if ("ios".equalsIgnoreCase(deviceInfo.osName)) {
            PackageBuilder.addString(parameters, "installed_at", deviceInfo.appInstallTime);
        }

        checkDeviceIds(parameters);
        return parameters;
    }

//    private Map<String, String> getGdprParameters() {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
//        Map<String, String> parameters = new HashMap<String, String>();
//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);
//
//        // Check if plugin is used and if yes, add read parameters.
//        if (imeiParameters != null) {
//            parameters.putAll(imeiParameters);
//        }
//
//        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);
//        if (oaidParameters != null) {
//            parameters.putAll(oaidParameters);
//        }
//
//        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
//        PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
//        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
//        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
//        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
//        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);
//
//        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
//            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
//            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
//            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
//        }
//
//        // Rest of the parameters.
//        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
//        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
//        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
//        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
//        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
//        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt);
//        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
//        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
//        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
//        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
//        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
//        PackageBuilder.addString(parameters, "fire_adid", Util.getFireAdvertisingId(contentResolver));
//        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", Util.getFireTrackingEnabled(contentResolver));
//        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
//        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
//        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
//        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
//        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
//        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
//
//        checkDeviceIds(parameters);
//        return parameters;
//    }

//    private Map<String, String> getDisableThirdPartySharingParameters() {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
//        Map<String, String> parameters = new HashMap<String, String>();
//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);
//
//        // Check if plugin is used and if yes, add read parameters.
//        if (imeiParameters != null) {
//            parameters.putAll(imeiParameters);
//        }
//
//        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);
//        if (oaidParameters != null) {
//            parameters.putAll(oaidParameters);
//        }
//
//        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
//        PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
//        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
//        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
//        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
//        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);
//
//        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
//            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
//            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
//            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
//        }
//
//        // Rest of the parameters.
//        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
//        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
//        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
//        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
//        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
//        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt);
//        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
//        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
//        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
//        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
//        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
//        PackageBuilder.addString(parameters, "fire_adid", Util.getFireAdvertisingId(contentResolver));
//        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", Util.getFireTrackingEnabled(contentResolver));
//        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
//        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
//        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
//        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
//        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
//        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
//
//        checkDeviceIds(parameters);
//        return parameters;
//    }

//    private Map<String, String> getAdRevenueParameters(String source, JSONObject adRevenueJson) {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
//        Map<String, String> parameters = new HashMap<String, String>();
//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);
//
//        // Check if plugin is used and if yes, add read parameters.
//        if (imeiParameters != null) {
//            parameters.putAll(imeiParameters);
//        }
//
//        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);
//        if (oaidParameters != null) {
//            parameters.putAll(oaidParameters);
//        }
//
//        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
//        PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
//        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
//        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
//        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
//        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);
//
//        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
//            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
//            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
//            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
//        }
//
//        // Rest of the parameters.
//        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
//        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
//        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
//        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
//        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
//        PackageBuilder.addLong(parameters, "connectivity_type", Util.getConnectivityType(adjustConfig.context));
//        PackageBuilder.addString(parameters, "country", deviceInfo.country);
//        PackageBuilder.addString(parameters, "cpu_type", deviceInfo.abi);
//        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt);
//        PackageBuilder.addString(parameters, "default_tracker", adjustConfig.defaultTracker);
//        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
//        PackageBuilder.addString(parameters, "device_manufacturer", deviceInfo.deviceManufacturer);
//        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
//        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
//        PackageBuilder.addString(parameters, "display_height", deviceInfo.displayHeight);
//        PackageBuilder.addString(parameters, "display_width", deviceInfo.displayWidth);
//        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
//        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
//        PackageBuilder.addString(parameters, "fb_id", deviceInfo.fbAttributionId);
//        PackageBuilder.addString(parameters, "fire_adid", Util.getFireAdvertisingId(contentResolver));
//        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", Util.getFireTrackingEnabled(contentResolver));
//        PackageBuilder.addString(parameters, "hardware_name", deviceInfo.hardwareName);
//        PackageBuilder.addString(parameters, "installed_at", deviceInfo.appInstallTime);
//        PackageBuilder.addString(parameters, "language", deviceInfo.language);
//        PackageBuilder.addDuration(parameters, "last_interval", activityStateCopy.lastInterval);
//        PackageBuilder.addString(parameters, "mcc", Util.getMcc(adjustConfig.context));
//        PackageBuilder.addString(parameters, "mnc", Util.getMnc(adjustConfig.context));
//        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
//        PackageBuilder.addLong(parameters, "network_type", Util.getNetworkType(adjustConfig.context));
//        PackageBuilder.addString(parameters, "os_build", deviceInfo.buildName);
//        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
//        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
//        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
//        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
//        PackageBuilder.addString(parameters, "screen_density", deviceInfo.screenDensity);
//        PackageBuilder.addString(parameters, "screen_format", deviceInfo.screenFormat);
//        PackageBuilder.addString(parameters, "screen_size", deviceInfo.screenSize);
//        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
//        PackageBuilder.addString(parameters, "source", source);
//        PackageBuilder.addJsonObject(parameters, "payload", adRevenueJson);
//        PackageBuilder.addLong(parameters, "session_count", activityStateCopy.sessionCount);
//        PackageBuilder.addDuration(parameters, "session_length", activityStateCopy.sessionLength);
//        PackageBuilder.addLong(parameters, "subsession_count", activityStateCopy.subsessionCount);
//        PackageBuilder.addDuration(parameters, "time_spent", activityStateCopy.timeSpent);
//        PackageBuilder.addString(parameters, "updated_at", deviceInfo.appUpdateTime);
//
//        checkDeviceIds(parameters);
//        return parameters;
//    }

//    private Map<String, String> getSubscriptionParameters(AdjustPlayStoreSubscription subscription, boolean isInDelay) {
//        ContentResolver contentResolver = adjustConfig.context.getContentResolver();
//        Map<String, String> parameters = new HashMap<String, String>();
//        Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger);
//
//        // Check if plugin is used and if yes, add read parameters.
//        if (imeiParameters != null) {
//            parameters.putAll(imeiParameters);
//        }
//
//        // Check if oaid plugin is used and if yes, add the parameter
//        Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger);
//        if (oaidParameters != null) {
//            parameters.putAll(oaidParameters);
//        }
//
//        // Device identifiers.
//        deviceInfo.reloadPlayIds(adjustConfig.context);
//        PackageBuilder.addString(parameters, "android_uuid", activityStateCopy.uuid);
//        PackageBuilder.addBoolean(parameters, "tracking_enabled", deviceInfo.isTrackingEnabled);
//        PackageBuilder.addString(parameters, "gps_adid", deviceInfo.playAdId);
//        PackageBuilder.addString(parameters, "gps_adid_src", deviceInfo.playAdIdSource);
//        PackageBuilder.addLong(parameters, "gps_adid_attempt", deviceInfo.playAdIdAttempt);
//
//        if (!containsPlayIds(parameters)) {
//            logger.warn("Google Advertising ID not detected, fallback to non Google Play identifiers will take place");
//            deviceInfo.reloadNonPlayIds(adjustConfig.context);
//            PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1);
//            PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5);
//            PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId);
//        }
//
//        // Callback and partner parameters.
//        if (!isInDelay) {
//            PackageBuilder.addMapJson(parameters, "callback_params", Util.mergeParameters(this.sessionParameters.callbackParameters, subscription.getCallbackParameters(), "Callback"));
//            PackageBuilder.addMapJson(parameters, "partner_params", Util.mergeParameters(this.sessionParameters.partnerParameters, subscription.getPartnerParameters(), "Partner"));
//        }
//
//        // Rest of the parameters.
//        PackageBuilder.addString(parameters, "api_level", deviceInfo.apiLevel);
//        PackageBuilder.addString(parameters, "app_secret", adjustConfig.appSecret);
//        PackageBuilder.addString(parameters, "app_token", adjustConfig.appToken);
//        PackageBuilder.addString(parameters, "app_version", deviceInfo.appVersion);
//        PackageBuilder.addBoolean(parameters, "attribution_deeplink", true);
//        PackageBuilder.addLong(parameters, "connectivity_type", Util.getConnectivityType(adjustConfig.context));
//        PackageBuilder.addString(parameters, "country", deviceInfo.country);
//        PackageBuilder.addString(parameters, "cpu_type", deviceInfo.abi);
//        PackageBuilder.addDateInMilliseconds(parameters, "created_at", createdAt);
//        PackageBuilder.addString(parameters, "default_tracker", adjustConfig.defaultTracker);
//        PackageBuilder.addBoolean(parameters, "device_known", adjustConfig.deviceKnown);
//        PackageBuilder.addString(parameters, "device_manufacturer", deviceInfo.deviceManufacturer);
//        PackageBuilder.addString(parameters, "device_name", deviceInfo.deviceName);
//        PackageBuilder.addString(parameters, "device_type", deviceInfo.deviceType);
//        PackageBuilder.addString(parameters, "display_height", deviceInfo.displayHeight);
//        PackageBuilder.addString(parameters, "display_width", deviceInfo.displayWidth);
//        PackageBuilder.addString(parameters, "environment", adjustConfig.environment);
//        PackageBuilder.addBoolean(parameters, "event_buffering_enabled", adjustConfig.eventBufferingEnabled);
//        PackageBuilder.addString(parameters, "external_device_id", adjustConfig.externalDeviceId);
//        PackageBuilder.addString(parameters, "fb_id", deviceInfo.fbAttributionId);
//        PackageBuilder.addString(parameters, "fire_adid", Util.getFireAdvertisingId(contentResolver));
//        PackageBuilder.addBoolean(parameters, "fire_tracking_enabled", Util.getFireTrackingEnabled(contentResolver));
//        PackageBuilder.addString(parameters, "hardware_name", deviceInfo.hardwareName);
//        PackageBuilder.addString(parameters, "installed_at", deviceInfo.appInstallTime);
//        PackageBuilder.addString(parameters, "language", deviceInfo.language);
//        PackageBuilder.addDuration(parameters, "last_interval", activityStateCopy.lastInterval);
//        PackageBuilder.addString(parameters, "mcc", Util.getMcc(adjustConfig.context));
//        PackageBuilder.addString(parameters, "mnc", Util.getMnc(adjustConfig.context));
//        PackageBuilder.addBoolean(parameters, "needs_response_details", true);
//        PackageBuilder.addLong(parameters, "network_type", Util.getNetworkType(adjustConfig.context));
//        PackageBuilder.addString(parameters, "os_build", deviceInfo.buildName);
//        PackageBuilder.addString(parameters, "os_name", deviceInfo.osName);
//        PackageBuilder.addString(parameters, "os_version", deviceInfo.osVersion);
//        PackageBuilder.addString(parameters, "package_name", deviceInfo.packageName);
//        PackageBuilder.addString(parameters, "push_token", activityStateCopy.pushToken);
//        PackageBuilder.addString(parameters, "screen_density", deviceInfo.screenDensity);
//        PackageBuilder.addString(parameters, "screen_format", deviceInfo.screenFormat);
//        PackageBuilder.addString(parameters, "screen_size", deviceInfo.screenSize);
//        PackageBuilder.addString(parameters, "secret_id", adjustConfig.secretId);
//        PackageBuilder.addLong(parameters, "session_count", activityStateCopy.sessionCount);
//        PackageBuilder.addDuration(parameters, "session_length", activityStateCopy.sessionLength);
//        PackageBuilder.addLong(parameters, "subsession_count", activityStateCopy.subsessionCount);
//        PackageBuilder.addDuration(parameters, "time_spent", activityStateCopy.timeSpent);
//        PackageBuilder.addString(parameters, "updated_at", deviceInfo.appUpdateTime);
//
//        PackageBuilder.addLong(parameters, "revenue", subscription.getPrice());
//        PackageBuilder.addDateInMilliseconds(parameters, "transaction_date", subscription.getPurchaseTime());
//        PackageBuilder.addString(parameters, "currency", subscription.getCurrency());
//        PackageBuilder.addString(parameters, "product_id", subscription.getSku());
//        PackageBuilder.addString(parameters, "receipt", subscription.getSignature());
//        PackageBuilder.addString(parameters, "purchase_token", subscription.getPurchaseToken());
//        PackageBuilder.addString(parameters, "billing_store", subscription.getBillingStore());
//        PackageBuilder.addString(parameters, "transaction_id", subscription.getOrderId());
//
//        checkDeviceIds(parameters);
//        return parameters;
//    }

    private ActivityPackage getDefaultActivityPackage(ActivityKind activityKind) {
        ActivityPackage activityPackage = new ActivityPackage(activityKind);
        activityPackage.setClientSdk(deviceInfo.clientSdk);
        return activityPackage;
    }

    public static void addString(Map<String, String> parameters, String key, String value) {
        if (TextUtils.isEmpty(value)) {
            return;
        }
        parameters.put(key, value);
    }

    public static void addBoolean(Map<String, String> parameters, String key, Boolean value) {
        if (value == null) {
            return;
        }
        int intValue = value ? 1 : 0;
        PackageBuilder.addLong(parameters, key, intValue);
    }

    static void addJsonObject(Map<String, String> parameters, String key, JSONObject jsonObject) {
        if (jsonObject == null) {
            return;
        }

        PackageBuilder.addString(parameters, key, jsonObject.toString());
    }

    static void addMapJson(Map<String, String> parameters, String key, Map<String, String> map) {
        if (map == null) {
            return;
        }
        if (map.size() == 0) {
            return;
        }

        JSONObject jsonObject = new JSONObject(map);
        String jsonString = jsonObject.toString();
        PackageBuilder.addString(parameters, key, jsonString);
    }

    public static void addLong(Map<String, String> parameters, String key, long value) {
        if (value < 0) {
            return;
        }
        String valueString = Long.toString(value);
        PackageBuilder.addString(parameters, key, valueString);
    }

    private static void addDateInMilliseconds(Map<String, String> parameters, String key, long value, String iso) {
        if (value <= 0) {
            return;
        }
        Date date = new Date(value);
        PackageBuilder.addDate(parameters, key, date, iso);
    }

    private static void addDateInSeconds(Map<String, String> parameters, String key, long value, String iso) {
        if (value <= 0) {
            return;
        }
        Date date = new Date(value * 1000);
        PackageBuilder.addDate(parameters, key, date, iso);
    }

    private static void addDate(Map<String, String> parameters, String key, Date value, String iso) {
        if (value == null) {
            return;
        }
//        String dateString = Util.dateFormatter.format(value);
        String dateString = Util.format(value, iso);
        PackageBuilder.addString(parameters, key, dateString);
    }

    private static void addDuration(Map<String, String> parameters, String key, long durationInMilliSeconds) {
        if (durationInMilliSeconds < 0) {
            return;
        }
        long durationInSeconds = (durationInMilliSeconds + 500) / 1000;
        PackageBuilder.addLong(parameters, key, durationInSeconds);
    }

    private static void addDouble(Map<String, String> parameters, String key, Double value) {
        if (value == null) {
            return;
        }
        String doubleString = Util.formatString("%.5f", value);
        PackageBuilder.addString(parameters, key, doubleString);
    }

    private boolean containsPlayIds(Map<String, String> parameters) {
        if (parameters == null) {
            return false;
        }
        return parameters.containsKey("gps_adid");
    }

    private void checkDeviceIds(Map<String, String> parameters) {
        if (parameters != null && !parameters.containsKey("mac_sha1") && !parameters.containsKey("mac_md5") && !parameters.containsKey("android_id") && !parameters.containsKey("gps_adid") && !parameters.containsKey("oaid") && !parameters.containsKey("imei") && !parameters.containsKey("meid") && !parameters.containsKey("device_id") && !parameters.containsKey("imeis") && !parameters.containsKey("meids") && !parameters.containsKey("device_ids") && !parameters.containsKey("idfa")) {
            System.out.println("Missing device id's. Please check if Proguard is correctly set with Adjust SDK");
        }
    }

    private String getEventSuffix(AdjustEvent event) {
        if (event.revenue == null) {
            return Util.formatString("'%s'", event.eventToken);
        } else {
            return Util.formatString("(%.5f %s, '%s')", event.revenue, event.currency, event.eventToken);
        }
    }


    public void setReferrerDetails(ReferrerDetails referrerDetails) {
//        clickTimeInSeconds
//        clickTimeServerInSeconds
//        installBeginTimeInSeconds
//        installBeginTimeServerInSeconds
//        installVersion
//        referrer
//        referrerApi
        clickTimeInSeconds = referrerDetails.getReferrerClickTimestampSeconds();
        clickTimeServerInSeconds = referrerDetails.getReferrerClickTimestampServerSeconds();
        installBeginTimeInSeconds = referrerDetails.getInstallBeginTimestampSeconds();
        installBeginTimeServerInSeconds = referrerDetails.getInstallBeginTimestampServerSeconds();
        installVersion = referrerDetails.getInstallVersion();
        referrer = referrerDetails.getInstallReferrer();
        referrerApi = "google";
    }

}
